/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upc.clase.demo.controller;

import edu.upc.clase.demo.entity.Credential;
import edu.upc.clase.demo.entity.CriterioBusqueda;
import edu.upc.clase.demo.entity.Contendor;
import edu.upc.clase.demo.service.ContendorService;
/*-------------*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/*-------------------*/
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Luis
 */
@Controller("contendorController")
public class ContendorController {

    @Autowired
    private ContendorService contendorService;
    private static Logger log = LoggerFactory.getLogger(ContendorController.class);

    @RequestMapping("/contendor/index")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView("contendor/index");
        List<Contendor> contendor = contendorService.buscarTodos();
        CriterioBusqueda criterioBusqueda = new CriterioBusqueda();
        mav.addObject("contendor", contendor);
        mav.addObject("criterioBusqueda",criterioBusqueda);
        return mav;
    }
    
    @RequestMapping(value = "/contendor/new", method = RequestMethod.GET)
    public ModelAndView newUsuario() {
        ModelAndView mav = new ModelAndView("contendor/new");
        Contendor contendor = new Contendor();
        mav.getModelMap().put("contendor", contendor);
        return mav;
    }

    @RequestMapping(value = "/contendor/new", method = RequestMethod.POST)
    public String createContendor(@ModelAttribute("contendor")Contendor contendor,
    SessionStatus status,HttpServletRequest request) {    
        
        try {
            MultipartFile avatar = contendor.getAvatar();
            if (avatar.getSize() > 0) {
                File dir = new File(request.getSession().getServletContext().getRealPath("") 
                                       + "/upload/");
                
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File destinationFile = new File(request.getSession().getServletContext().getRealPath("") 
                                       + "/upload/"+ contendor.getNocontendor()+avatar.getOriginalFilename());
                avatar.transferTo(destinationFile);
           }
           contendor.setNoimagen(avatar.getOriginalFilename());
           contendorService.insertar(contendor);
        } catch (IOException iOException) {
            log.error("No se pudo guardar la imagen");
        }
        status.setComplete();
        return "redirect:/pages/contendor/index";
        
    }
    
    @RequestMapping(value = "/contendor/edit", method = RequestMethod.GET)
    public ModelAndView editContendor(@RequestParam("id")Integer id) {    
        ModelAndView mav = new ModelAndView("contendor/edit");
        Contendor contendor = contendorService.buscar(id);
        mav.getModelMap().put("contendor", contendor);
        return mav;        
    }
    
    @RequestMapping(value="/contendor/edit", method=RequestMethod.POST)
    public String update(@ModelAttribute("contendor") Contendor contendor,
    SessionStatus status,HttpServletRequest request) {
        
         try {
            MultipartFile avatar = contendor.getAvatar();

            if (avatar.getSize() > 0) {
                File dir = new File(request.getSession().getServletContext().getRealPath("") 
                                       + "/upload/");
                
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File destinationFile = new File(request.getSession().getServletContext().getRealPath("") 
                                       + "/upload/"+ avatar.getOriginalFilename());
                avatar.transferTo(destinationFile);
                             
            }
               contendor.setNoimagen(avatar.getOriginalFilename());
           contendorService.actualizar(contendor);
        } catch (IOException iOException) {
            log.error("No se pudo guardar la imagen");
        }
        status.setComplete();
        return "redirect:/pages/contendor/index";
    }
    
    @RequestMapping("/contendor/delete")
    public ModelAndView delete(@RequestParam("id")Integer id)
    {
        ModelAndView mav = new ModelAndView("redirect:/pages/contendor/index");
        Contendor contendor = contendorService.buscar(id);
        contendorService.eliminar(contendor);
        return mav;
    }
    
    @RequestMapping("/contendor/login")
    public ModelAndView login() {
        ModelAndView mav = new ModelAndView("contendor/login");
        Credential credential = new Credential();
        mav.getModelMap().put("credential", credential);
        return mav;
    }    
    
    @RequestMapping("/contendor/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/pages/contendor/login";
    }        
    
    
    @RequestMapping(value = "/contendor/buscar", method=RequestMethod.POST)
    public ModelAndView buscar(@ModelAttribute("criterioBusqueda") CriterioBusqueda criterio, SessionStatus status) {
        ModelAndView mav = new ModelAndView("contendor/resultadoBusqueda");
        log.info("resultado = " + contendorService.buscarPorNombre(criterio.getNombre()).size());
        mav.getModel().put("resultado",contendorService.buscarPorNombre(criterio.getNombre()));
        return mav;
    }
    
    
}
